package com.ch.http.v1.impl;

import com.ch.http.v1.Cookie;
import com.ch.http.v1.HttpServletImp;
import com.ch.http.v1.HttpServletRequest;
import com.ch.http.v1.HttpServletResponse;

import javax.servlet.annotation.WebServlet;
import java.io.PrintWriter;

@WebServlet("/cookie.s")
public class CookieServlet extends HttpServletImp {

    /**
     * cookie : 浏览器保存少量数据的技术
     * 少量: 4k 50个数据项
     * 储存位置: 1.没有有效期=>内存 2.有有效期=>硬盘=>临时文件
     * 属性: name,value,path,domain...
     * 特点: 浏览器默认每次放送请求时,都会带上cookie数据,返回给服务器
     *      服务器也可以主动推送 cookie
     */

    public void doGet(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for(Cookie cookie : cookies){
                out.append("<li>")
                        .append(cookie.getName())
                        .append("=")
                        .append(cookie.getValue())
                        .append("</li>");
            }
        }
        //添加cookie
        String add = request.getParameter("add");
        // 移除cookie
        String del = request.getParameter("del");

        Cookie cookie1 = new CookieImpl("add",add);
        Cookie cookie2 = new CookieImpl(del,null);
        cookie2.setMaxAge(0); // 0 秒 ,有效期

        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}
